package net.j4love.zookeeper.quickstart;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author He Peng
 * @create 2017-05-15 13:58
 * @update 2017-05-15 13:58
 * @see
 */
public class AsyncCreateZNode {

    private static final Logger LOG = LoggerFactory.getLogger(AsyncCreateZNode.class);

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

        ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 1000, null);
        Stat stat = zk.exists("/test_async_create_node", null);
        if (stat == null){

            // 异步创建临时节点
            zk.create("/test_async_create_node", "hello world!".getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new AsyncCallback.StringCallback() {
                        @Override
                        public void processResult(int rc, String path, Object ctx, String name) {

                            System.err.println("rc = " + rc + "\r\n" +
                                        "path = " + path + "\r\n" +
                                        "ctx = " + ctx + "\r\n" +
                                        "name = " + name);
                        }
                    } ,"async create ephemeral znode callback");

        }

        byte[] dataByte = zk.getData("/test_async_create_node", null, null);
        String dataStr = new String(dataByte, "UTF-8");

        LOG.debug("/test_async_create_node node data {} " , dataStr);

        TimeUnit.SECONDS.sleep(10);

        zk.close();
    }
}
